package cn.schoolwow.quickflow.domain;

import cn.schoolwow.quickflow.QuickFlow;
import com.alibaba.fastjson.JSONArray;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 主流程列表配置
 * */
public class FlowExecutorRootConfig {
    /**
     * 流程唯一标识
     * */
    public Long id;

    /**
     * 流程备注
     * */
    public ThreadLocal<StringBuilder> remarkBuilderThreadLocal = new ThreadLocal<>();

    /**
     * 上下文数据
     */
    public Map<String, Object> dataMap = new ConcurrentHashMap<>();

    /**
     * 线程本地数据
     */
    public ThreadLocal<Map<String, Object>> threadLocalDataMap = new ThreadLocal<>();

    /**
     * 流程上下文数据key列表
     * */
    public FlowContextDataKeySet flowContextDataKeySet = new FlowContextDataKeySet();

    /**
     * 打印路径
     * */
    public final StringBuilder printTraceBuilder = new StringBuilder();

    /**
     * 流程异常
     */
    public Exception exception;

    /**
     * 中断原因
     */
    public String brokenReason;

    /**
     * 流程下标记录
     */
    public AtomicInteger index = new AtomicInteger(0);

    /**
     * 流程列表
     */
    public JSONArray flowArray = new JSONArray();

    /**
     * 流程层级
     */
    public ThreadLocal<Integer> flowLevel = new ThreadLocal<Integer>();

    /**
     * 全局流程配置
     */
    public FlowConfig flowConfig;

    /**
     * QuickFlow对象
     */
    public QuickFlow quickFlow;

    /**
     * 是否开启当前流程日志记录
     * */
    public boolean startRecord;

    /**
     * 执行日志记录
     * */
    public StringBuilder recordBuilder = new StringBuilder();

    /**
     * 是否开启用户日志记录
     * */
    public boolean enableUserLog;

    /**
     * 用户日志
     * */
    public StringBuffer userLog = new StringBuffer();

    /**
     * 增加层级
     */
    public void incrementFlowLevel() {
        Integer flowLevel = this.flowLevel.get();
        if (null == flowLevel) {
            this.flowLevel.set(1);
        } else {
            int newFlowLevel = flowLevel + 1;
            this.flowLevel.set(newFlowLevel);
        }
    }

    /**
     * 减少层级
     */
    public void decrementFlowLevel() {
        Integer flowLevel = this.flowLevel.get();
        if (null == flowLevel) {
            this.flowLevel.set(0);
        } else {
            int newFlowLevel = flowLevel - 1;
            this.flowLevel.set(newFlowLevel);
        }
    }
}